<template>
	<conf-module-container ref="refConfModuleContainer" class="add-box-container">
		<template #Slot-Conf-Module-Header>
			<global-svg-icon
				icon-name="return"
				width="18px"
				height="18px"
				class="header-icon"
				style="margin-right: 8px; cursor: pointer"
				@click="router.go(-1)"
			></global-svg-icon>
			<p class="font-20-bold bread-crumb-title" style="color: #f0f6fc">新增盒子</p>
		</template>

		<template #Slot-Conf-Module-Content>
			<div style="display: flex">
				<div class="the-add-box-config">
					<div class="font-16-bold the-common-title">
						<global-svg-icon
							icon-name="config-title-tri"
							width="3px"
							height="18px"
							style="margin-right: 16px; cursor: pointer"
						></global-svg-icon>
						<div>新增盒子</div>
					</div>
					<div class="the-add-box">
						<div class="prompt">
							<global-svg-icon icon-name="error-warning-line" width="20px" height="20px"></global-svg-icon> <br />
							请确保平台已完成MQTT配置,镜鉴魔盒设备已经完成网络配置,否则将无法通过局域网搜索到该设备
						</div>

						<a-button :disabled="isSearch" class="search-btn" @click="searchDevice">
							<global-svg-icon icon-name="search-line" width="20px" height="20px"></global-svg-icon
							>{{ isSearch ? `搜索局域网内设备 (${timer}s)` : '搜索局域网内设备' }}
						</a-button>

						<div class="result-title">搜索结果</div>
						<div v-if="!isResultFrame" class="no-result-frame">暂无搜索结果</div>
						<div v-else class="result-frame">
							<a-table
								:pagination="false"
								:row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }"
								:row-key="rowKey"
								:columns="columns"
								:data-source="resultData"
							></a-table>
						</div>
						<div>
							<a-button type="primary" html-type="submit" class="form-button" style="margin-right: 8px" @click="addBoxEvent">添加</a-button>
							<a-button @click="cancelModal">取消</a-button>
						</div>
					</div>
				</div>
			</div>
		</template>
	</conf-module-container>
</template>

<script setup lang="ts" name="box-add">
import { exceedAuthority } from '@/global-utils/base.utils';
import { ConfModuleContainer } from '../../components/index';
import { AddBoxManageApi } from '../../api';
import { appStore } from '@/global-store/index';

const { WebSocketStore } = appStore;
const { SocketState, ScoketSend } = WebSocketStore;

const $message: any = inject('$message');
const router = useRouter();
const isResultFrame = ref(false); // 是否有搜索结果
const resultData = ref<any>([]); // 表格数据
const rowKey = ref<string>('terminalId');

const token = window.sessionStorage.getItem('token');

const timer = ref(30);
// 搜索局域网内设备
const isSearch = ref(false);
const searchDevice = async (): Promise<void> => {
	let res: TsRes = await AddBoxManageApi.searchBox();
	console.log(res);
	if (res.code === 0) {
		resultData.value = [];
		isResultFrame.value = true;
	}

	isSearch.value = true;
	const times = setInterval(() => {
		if (timer.value === 0) {
			clearInterval(times);
			isSearch.value = false;
			timer.value = 30;
			return;
		} else if (!isSearch.value) {
			// 弹层关闭 清空倒计时
			timer.value = 30;
			isSearch.value = false;
			return;
		}
		timer.value--;
	}, 1000);

	// 搜索接口
};

// ========================================
type Key = string | number;

const columns = [
	{
		title: 'SN码',
		dataIndex: 'terminalId',
		width: '286px'
	},
	{
		title: 'IP地址',
		dataIndex: 'terminalIp'
	}
];

const state = reactive<{
	selectedRowKeys: Key[];
	selectedRows: any[];
	loading: boolean;
}>({
	selectedRowKeys: [], // Check here to configure the default column
	selectedRows: [],
	loading: false
});

const onSelectChange = (selectedRowKeys: Key[], selectedRows: any[]): void => {
	console.log('selectedRowKeys changed: ', selectedRowKeys, selectedRows);
	state.selectedRowKeys = selectedRowKeys;
	state.selectedRows = selectedRows;
};
// ==============================================
// 取消
const cancelModal = (): void => {
	router.go(-1);
};
// 添加盒子
const addBoxEvent = async (): Promise<void> => {
	console.log(state.selectedRowKeys.length, '是否选中搜索结果');
	// 添加接口
	if (state.selectedRowKeys.length <= 0) {
		$message.warning('请至少选择一个盒子设备');
	} else {
		let params = state.selectedRows.map((item: any) => {
			return {
				boxSerial: item.terminalId,
				boxIp: item.terminalIp
			};
		});
		console.log('params:', params);

		let res: TsRes = await AddBoxManageApi.saveBatchBoxs(params);
		console.log(res);
		if (res.code === 0) {
			$message.success('已经添加成功，请注意刷新页面查看');
		}
	}
};

SocketState.ws.onmessage = (info: { data: string }) => {
	let obj = JSON.parse(info.data);
	if (obj) {
		exceedAuthority(obj);
		if (obj.message === 'searchBoxs') {
			resultData.value.push(obj as never);
		}
	}
};

onMounted(() => {
	ScoketSend({ webPage: 'searchLanBoxS', userId: token, stater: 0 });
});
onUnmounted(() => {
	ScoketSend({ webPage: 'searchLanBoxS', userId: token, stater: 1 });
});
</script>

<style lang="less">
.add-box-container {
	.ant-select-selector,
	.ant-input-password {
		border: 1px solid @borderColor02 !important;
		border-radius: 6px !important;
		color: @text01 !important;
		background-color: transparent !important;
	}

	.ant-table-cell {
		border-bottom: 1px solid @borderColor02 !important;
	}

	.ant-table-selection-column {
		border: 0 !important;
	}

	.ant-form {
		.ant-form-item {
			.ant-form-item-label {
				margin-top: 32px;
			}
		}
	}

	.the-common-title {
		display: flex;
		margin-bottom: 16px;
		color: @text01;
		align-items: center;
	}

	.the-add-box-config {
		margin: 0 auto;

		.the-add-box {
			width: 570px;
			border: @borderColor01;
			border-radius: 4px;
			padding: 20px 20px 40px;
			background: @background02;
			box-shadow: 0 40px 180px 0 rgba(0, 0, 0, 0.35);

			.prompt {
				border-radius: 6px;
				padding: 15px;
				font-size: 14px;
				line-height: 22px;
				color: @text02;
				background: @mask04;
			}

			.search-btn {
				display: flex;
				width: 170px;
				height: 36px;
				margin: 32px 0;
				border: 1px solid @mask01;
				border-radius: 6px;
				padding: 7px 16px;
				font-size: 14px;
				line-height: 22px;
				text-align: center;
				color: @text01;
				background: @primary01;
				box-shadow: 0 2px 0 0 rgba(0, 0, 0, 0.04);
				cursor: pointer;
				justify-content: center;
				align-items: center;
				gap: 6px;
			}

			.search-btn-disable {
				width: 170px;
				height: 36px;
				margin: 32px 0;
				border: 1px solid @mask01;
				border-radius: 6px;
				padding: 7px 16px;
				line-height: 22px;
				text-align: center;
				color: @text01;
				background: @mask01;
				cursor: pointer;
				justify-content: center;
				align-items: center;
			}

			.result-title {
				margin-bottom: 8px;
				font-size: 16px;
				font-weight: 700;
				font-style: normal;
				line-height: 24px;
				color: @text01;
			}

			.no-result-frame {
				display: flex;
				width: 520px;
				height: 181px;
				margin-bottom: 32px;
				border: 1px solid @borderColor02;
				border-radius: 6px;
				line-height: 22px;
				color: @text03;
				justify-content: center;
				align-items: center;
			}

			.result-frame {
				margin: 8px 0 32px;
				border: 1px solid @borderColor02;
				border-radius: 6px;
			}
		}
	}
}
</style>
